import React, { useEffect } from 'react';
import { Row, Col, Card, Statistic, Typography, Button, Tag, Table } from 'antd';
import {
  ArrowUpOutlined,
  ArrowDownOutlined,
  PlusOutlined,
  EyeOutlined,
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { useAppDispatch, useAppSelector } from '../store/hooks';
import { fetchPortfolios } from '../store/slices/portfolioSlice';
import { fetchRecommendations } from '../store/slices/productSlice';
import { useAuth } from '../hooks/useAuth';
import MainLayout from '../components/Layout/MainLayout';
import ResizableTable from '../components/ResizableTable';
import { RISK_LEVELS } from '../types';

const { Title, Text } = Typography;

const Dashboard: React.FC = () => {
  const navigate = useNavigate();
  const dispatch = useAppDispatch();
  const { user } = useAuth();
  const { portfolios, loading: portfolioLoading } = useAppSelector((state: any) => state.portfolio);
  const { recommendations, loading: productLoading } = useAppSelector((state: any) => state.product);

  useEffect(() => {
    dispatch(fetchPortfolios());
    if (user?.risk_level) {
      dispatch(fetchRecommendations(user.risk_level));
    }
  }, [dispatch, user?.risk_level]);

  // 计算总资产统计
  const portfolioList = Array.isArray(portfolios) ? portfolios : [];
  const totalAssets = portfolioList.reduce((sum: number, portfolio: any) => sum + portfolio.total_value, 0);
  const totalReturn = portfolioList.reduce((sum: number, portfolio: any) => sum + portfolio.total_return, 0);
  const totalReturnRate = totalAssets > 0 ? (totalReturn / totalAssets) * 100 : 0;

  // 投资组合表格列
  const portfolioColumns = [
    {
      title: '组合名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: string, record: any) => (
        <Button
          type="link"
          onClick={() => navigate(`/portfolio/${record.id}`)}
          style={{ padding: 0 }}
        >
          {text}
        </Button>
      ),
    },
    {
      title: '总价值',
      dataIndex: 'total_value',
      key: 'total_value',
      render: (value: number) => `¥${value ? value.toLocaleString() : '0'}`,
    },
    {
      title: '总收益',
      dataIndex: 'total_return',
      key: 'total_return',
      render: (value: number) => (
        <Text type={value >= 0 ? 'success' : 'danger'}>
          {value >= 0 ? '+' : ''}¥{value ? value.toLocaleString() : '0'}
        </Text>
      ),
    },
    {
      title: '风险等级',
      dataIndex: 'risk_level',
      key: 'risk_level',
      render: (level: number) => (
        <Tag color={level <= 2 ? 'green' : level <= 3 ? 'orange' : 'red'}>
          {RISK_LEVELS[level as keyof typeof RISK_LEVELS]}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: any) => (
        <Button
          type="link"
          icon={<EyeOutlined />}
          onClick={() => navigate(`/portfolio/${record.id}`)}
        >
          查看详情
        </Button>
      ),
    },
  ];

  // 推荐产品表格列
  const productColumns = [
    {
      title: '产品名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: string, record: any) => (
        <Button
          type="link"
          onClick={() => navigate(`/products/${record.id}`)}
          style={{ padding: 0 }}
        >
          {text}
        </Button>
      ),
    },
    {
      title: '产品代码',
      dataIndex: 'code',
      key: 'code',
    },
    {
      title: '风险等级',
      dataIndex: 'risk_level',
      key: 'risk_level',
      render: (level: number) => (
        <Tag color={level <= 2 ? 'green' : level <= 3 ? 'orange' : 'red'}>
          {RISK_LEVELS[level as keyof typeof RISK_LEVELS]}
        </Tag>
      ),
    },
    {
      title: '最小投资额',
      dataIndex: 'min_investment',
      key: 'min_investment',
      render: (value: number) => `¥${value ? value.toLocaleString() : '0'}`,
    },
  ];



  return (
    <MainLayout>
      <div>
        <div style={{ marginBottom: 24 }}>
          <Title level={2}>仪表盘</Title>
          <Text type="secondary">
            欢迎回来，{user?.real_name || user?.username}！
          </Text>

        </div>

        {/* 资产概览 */}
        <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
          <Col xs={24} sm={12} lg={6}>
            <Card>
              <Statistic
                title="总资产"
                value={user?.total_assets || 0}
                precision={2}
                valueStyle={{ color: '#1890ff' }}
                prefix="¥"
              />
            </Card>
          </Col>
          <Col xs={24} sm={12} lg={6}>
            <Card>
              <Statistic
                title="可用现金"
                value={user?.available_cash || 0}
                precision={2}
                valueStyle={{ color: '#52c41a' }}
                prefix="¥"
              />
            </Card>
          </Col>
          <Col xs={24} sm={12} lg={6}>
            <Card>
              <Statistic
                title="投资组合价值"
                value={totalAssets}
                precision={2}
                valueStyle={{ color: '#722ed1' }}
                prefix="¥"
              />
            </Card>
          </Col>
          <Col xs={24} sm={12} lg={6}>
            <Card>
              <Statistic
                title="总收益率"
                value={totalReturnRate}
                precision={2}
                valueStyle={{ color: totalReturnRate >= 0 ? '#52c41a' : '#ff4d4f' }}
                prefix={totalReturnRate >= 0 ? <ArrowUpOutlined /> : <ArrowDownOutlined />}
                suffix="%"
              />
            </Card>
          </Col>
        </Row>

        <Row gutter={[16, 16]}>
          {/* 投资组合 */}
          <Col xs={24} lg={14}>
            <Card
              title="我的投资组合"
              extra={
                <Button
                  type="primary"
                  icon={<PlusOutlined />}
                  onClick={() => navigate('/portfolio')}
                >
                  创建组合
                </Button>
              }
            >
              <ResizableTable
                columns={portfolioColumns}
                dataSource={portfolioList}
                loading={portfolioLoading}
                rowKey="id"
                pagination={false}
                size="small"
              />
            </Card>
          </Col>

          {/* 推荐产品 */}
          <Col xs={24} lg={10}>
            <Card
              title="推荐产品"
              extra={
                <Button
                  type="link"
                  onClick={() => navigate('/products')}
                >
                  查看更多
                </Button>
              }
            >
              <ResizableTable
                columns={productColumns}
                dataSource={Array.isArray(recommendations) ? recommendations.slice(0, 5) : []}
                loading={productLoading}
                rowKey="id"
                pagination={false}
                size="small"
              />
            </Card>
          </Col>
        </Row>
      </div>
    </MainLayout>
  );
};

export default Dashboard;